<script>
import { useSiteDataApi, useArticleApi } from "@/api/homePage";
import ZPMixin from '@/uni_modules/z-paging/components/z-paging/js/z-paging-mixin';
import Config from "@/config";
import HzSafeArea from "@/components/layout/hz/hz-safe-area.vue";
import {getGoodsList, getProductTagGroup, getShopTypeList} from '@/api/mall.js';
import navBar from "@/components/layout/navbar/index.vue";

export default {
  name: "index",
  components: {navBar, HzSafeArea },
  mixins: [ZPMixin],
  data() {
    return {
      navBgColor: 'transparent',
      loading: true,
      // banner数据
      banner: [],
      // 商品分类
      categoryList: [],
      // 推荐产品
      recommendProducts: [],
      // banner图片列表
      bannerUrls: [],
      // 搜索参数
      searchParams: {
        IsRecommend: 1,
        TypeId: 2,
        PurchaseMethod: "0"
      },
      // 加载状态
      loadingStatus: "loadmore",
      // 当前页数
      pageIndex: 1,
      // 每页条数
      pageSize: 10
    }
  },
  watch: {
    '$i18n.locale'() {
      // 监听语言变化，重新设置导航栏标题
      this.setNavigationTitle();
    }
  },
  computed: {
    // banner图片地址
    bannerUrl() {
      return this.banner?.map(item => item.CoverImg || item.ImgUrl)
    },
    safeAreaTop(){
      return this.$store.state.app.wxMenuClient.top
    },
  },
  onLoad() {
    // 设置导航栏标题
    this.setNavigationTitle();
    this.init();
  },
  methods: {
    handlePageScroll(e) {
      const scrollTop = e.detail.scrollTop;
      if (scrollTop > 150) {
        this.navBgColor = '#fff';
      } else {
        this.navBgColor = 'transparent';
      }
    },
    // 初始化
    async init() {
      try {
        this.loading = true;

        // 并行加载banner和商品分类
        await Promise.all([
          this.loadBanner(),
          this.loadCategoryList()
        ]);

        // 不在这里调用reload，而是在onLoad之后的生命周期中调用
      } catch (error) {
        console.error("初始化错误:", error);
      } finally {
        this.loading = false;
      }
    },

    // 加载banner
    async loadBanner() {
      try {
        // 这里使用首页配置中的banner模块ID，实际使用时应替换为商城页面的banner模块ID
        const res = await useArticleApi({
          ArticleCategoryId: Config.site.mall_banner_id
        });
        if (res && res.Data) {
          this.banner = res.Data;
        }
      } catch (error) {
        console.error("加载banner失败:", error);
      }
    },

    // 加载商品分类
    async loadCategoryList() {
      try {
        const res = await getProductTagGroup({
          Index: 1,
          Size: 50,
          ParentId: 2
        });
        
        if (res && res.Data) {
          this.categoryList = res.Data.map(item => {
            return {
              title: item.Name,
              value: item.Id,
              icon: item.ImgUrl
            };
          });
        }
      } catch (error) {
        console.error("加载商品分类失败:", error);
      }
    },

    // 分页加载推荐产品
    async queryList(pageNo, pageSize) {
      try {
        this.loading = true;
        // 从store获取选中的位置
        const selectedLocation = this.$store.state.base.selectedLocation;

        const { Data } = await getGoodsList({
          Index: pageNo,
          Size: pageSize,
          BusinessAreaId: selectedLocation.value,
          ...this.searchParams
        });
        
        // 完成加载
        this.$refs.paging.complete(Data || []);
      } catch (error) {
        console.error("获取商品失败:", error);
        this.$refs.paging.complete(false);
      } finally {
        this.loading = false;
      }
    },

    // 商品详情
    goToProductDetail(id) {
      uni.navigateTo({
        url: `/mall_subpages/goods/index?id=${id}&type=2&bookType=sc&shoppingCart=true`
      });
    },

    // 根据分类筛选商品
    selectCategory(data) {
      uni.navigateTo({
        url: `/mall_subpages/mall/zone?id=${data.value}&title=${data.title}`
      })
    },

    // 商家详情
    goToMerchantDetail(id) {
      uni.navigateTo({
        url: `/mall_subpages/merchants/detail?id=${id}`
      });
    },
    locationChanged(){
      this.$refs.paging.reload()
    },

    // 设置导航栏标题
    setNavigationTitle() {
      uni.setNavigationBarTitle({
        title: this.$t('mall.index.title')
      });
    }
  }
}
</script>

<template>
  <z-paging
      ref="paging"
      v-model="recommendProducts"
      @query="queryList"
      height="100vh"
      :paging-style="{minHeight: '100vh', backgroundColor: '#F5F6F7'}"
      :default-page-size="6"
      :auto-scroll-to-top-when-reload="false"
      :show-scrollbar="false"
  >
    <scroll-view
      scroll-y 
      style="height: 100vh"
      @scroll="handlePageScroll"
    >
      <u-navbar
        :title="$t('mall.index.title')"
        :bgColor="navBgColor"
        fixed
        :autoBack="true"
      />
      <view class="header-bg" :style="{top: safeAreaTop + 'px'}">
        <!-- Banner轮播 -->
        <view class="banner-container">
          <u-swiper
              :list="bannerUrl"
              indicatorMode="dot"
              indicator
              height="450rpx"
              borderRadius="12"
          ></u-swiper>
        </view>
      </view>

    <!-- 商品分类 -->
    <view class="section-container category-section">
      <scroll-view class="category-scroll" scroll-x show-scrollbar="false">
        <view class="category-list-horizontal">
          <view
              class="category-item-horizontal"
              v-for="(item, index) in categoryList"
              :key="index"
              @click="selectCategory(item)"
          >
            <view class="category-icon-wrapper">
              <image :src="item.icon" mode="aspectFill" class="category-icon"></image>
            </view>
            <view class="category-title">{{item.title}}</view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 推荐产品 -->
    <view class="section-container recommend-product-section">
      <view class="product-grid">
        <view
            class="product-item"
            v-for="(item, index) in recommendProducts"
            :key="index"
            @click="goToProductDetail(item.Id)"
        >
          <image :src="item.Img" mode="aspectFill" class="product-image"></image>
          <view class="product-info">
            <text class="product-name">{{item.Name || '商品名称'}}</text>
            <view class="product-price-row">
              <text class="product-price">¥ {{item.ShowPrice || 0}}</text>
<!--              <text class="product-sales">{{item.SalesCount || 0}}人购买</text>-->
            </view>
          </view>
        </view>
      </view>
    </view>
    </scroll-view>

<!--    <template #bottom>-->
<!--      <hz-safe-area></hz-safe-area>-->
<!--    </template>-->
  </z-paging>
</template>

<style scoped lang="scss">
.header-bg {
  background: url("https://wzws.wanshanlundiao.cn/upload/img/20250408/202504081041149219.png") no-repeat;
  background-size: cover;
}

/* 公共部分 */
.section-container {
  margin: 20rpx 0;
  background-color: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;
}
.section-header {
  padding: 20rpx;
  border-bottom: 1rpx solid #f2f2f2;
}
.section-title {
  font-family: PingFang SC;
  font-weight: bold;
  font-size: 36rpx;
  color: #333333;
  line-height: 36rpx;
  position: relative;
  display: inline-block;
  padding-bottom: 10rpx;
}

/* 热门商家标题下划线 */
//.section-title::after {
//  content: '';
//  position: absolute;
//  left: 50%;
//  transform: translateX(-50%);
//  bottom: 0;
//  width: 50rpx;
//  height: 6rpx;
//  background-color: #B6E7FD;  /* 浅蓝色 */
//  display: block;
//  border-radius: 2rpx;
//}

/* 推荐产品标题下划线 */
.recommend-product-section .section-title::after {
  background-color: #B6E7FD;  /* 使用相同的浅蓝色 */
  width: 50rpx;  /* 相同的宽度 */
}

/* 商品分类 */
.category-scroll {
  width: 100%;
  white-space: nowrap;
  padding: 20rpx 0;
}
.category-list-horizontal {
  display: flex;
  padding: 0 20rpx;
}
.category-item-horizontal {
  width: 140rpx;
  margin-right: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  flex-shrink: 0;
}
.category-item-horizontal .category-icon-wrapper {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  overflow: hidden;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
}
.category-item-horizontal .category-icon {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.category-item-horizontal .category-title {
  font-size: 24rpx;
  color: #333;
  margin-top: 10rpx;
  text-align: center;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 推荐产品 */
.product-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx;
  justify-content: space-between;
}
.product-item {
  width: 48%;
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}
.product-item:nth-child(odd) {
  margin-right: 0;
}
.product-item .product-image {
  width: 100%;
  height: 320rpx;
  border-radius: 12rpx 12rpx 0 0;
  object-fit: cover;
  display: block;
}
.product-item .product-info {
  padding: 16rpx;
}
.product-item .product-info .product-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 6rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  height: auto;
  line-height: 1.3;
}
.product-item .product-info .product-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 4rpx;
}
.product-item .product-info .product-price-row .product-price {
  font-size: 32rpx;
  color: #FF4B31;
  font-weight: bold;
}
.product-item .product-info .product-price-row .product-sales {
  font-size: 24rpx;
  color: #999;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
.category-item-horizontal, .product-item {
  animation: fadeIn 0.5s ease-out;
}
</style>
